package mc933.proj.clickposition;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;

import android.app.AlertDialog;
import android.content.Context;
import android.graphics.drawable.Drawable;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.OverlayItem;

public class MapPoints extends ItemizedOverlay<OverlayItem> {

	private ArrayList<OverlayItem> overlays = new ArrayList<OverlayItem>();
	private Context context;

	public MapPoints(Context context, Drawable defaultMarker,
			String listPointsStr) {
		super(boundCenterBottom(defaultMarker));
		this.context = context;
		JSONArray listPoints;
		try {
			listPoints = new JSONArray(listPointsStr);

			int position = 1;

			for (int i = listPoints.length() - 1; i >= 0; i--) {
				JSONArray coord = listPoints.getJSONArray(i);

				Double latitude = (Double.parseDouble(coord.getString(0))) * 1E6;
				Double longitude = (Double.parseDouble(coord.getString(1))) * 1E6;

				GeoPoint point = new GeoPoint(latitude.intValue(),
						longitude.intValue());

				addOverlay(new OverlayItem(point, "Point " + position,
						latitude.toString() + ";" + longitude.toString()));

			}

		} catch (JSONException e) {
			e.printStackTrace();
		}

	}

	@Override
	protected OverlayItem createItem(int i) {
		return overlays.get(i);
	}

	@Override
	public int size() {
		return overlays.size();
	}

	public void addOverlay(OverlayItem overlay) {
		overlays.add(overlay);
		populate();
	}

	@Override
	protected boolean onTap(int index) {
		OverlayItem item = overlays.get(index);

		AlertDialog.Builder dialog = new AlertDialog.Builder(this.context);
		dialog.setTitle(item.getTitle());
		dialog.setMessage(item.getSnippet());
		dialog.show();
		return true;
	}
}
